<template>
  <div>
    <PageTool :is-show="true">
      <span slot="left">共{{ pageInfo.total }}条记录</span>
      <template v-slot:right>
        <!-- @click="comExportToExcel" -->
        <el-button size="small" type="danger" @click="exportToExcel">普通excel导出</el-button>
        <el-button size="small" type="info" @click="comExportToExcel">复杂excel导出</el-button>
        <el-button size="small" type="success" @click="$router.push({name:'import',query:{type:'user'}})">excel导入</el-button>
        <el-button size="small" type="primary" @click="dialogVisible = true">新增员工</el-button>
      </template>
    </PageTool>
    <el-table v-loading="loading" :data="list" border stripe>
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="姓名" prop="username" width="100" sortable align="center" />
      <el-table-column label="头像" prop="staffPhoto" width="120" class-name="avator">
        <template slot-scope="{row}">
          <img v-imgError="defaultImg" :src="row.staffPhoto" style="width:70px; height: 70px; border-radius: 50%;object-fit: cover;" @click="preview(row.staffPhoto)">
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="mobile" width="120" sortable />
      <el-table-column label="工号" prop="workNumber" width="140" sortable align="center" />
      <el-table-column label="聘用形式" prop="formOfEmployment" width="120" sortable align="center" :formatter="formatterEmployee" />
      <el-table-column label="部门" prop="departmentName" width="100" sortable align="center" />
      <el-table-column label="入职时间" prop="timeOfEntry" width="120" sortable>
        <template v-slot="{row}">
          <span>{{ row.timeOfEntry | formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        prop="enableState"
        width="100"
        sortable
        :filters="[{text: '可用', value: '1'}, {text: '不可用', value: '2'}]"
        :filter-method="filterHandler"
      >
        <template v-slot="{row}">
          <el-switch
            :value="Number(row.enableState) === 1"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" sortable>
        <template v-slot="{row}">
          <el-row type="flex">
            <el-button size="mini" type="text" @click="$router.push({name: 'details',params:{id:row.id} })">查看</el-button>
            <el-button size="mini" type="text">转正</el-button>
            <el-button size="mini" type="text">调岗</el-button>
            <el-button size="mini" type="text">离职</el-button>
            <el-button size="mini" type="text" @click="assignRole(row.id)">角色</el-button>
            <el-button size="mini" type="text" @click="delEmploy(row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <el-row tyep="flex" justify="end">
      <el-col>
        <el-pagination
          layout="prev, pager, next"
          :total="pageInfo.total"
          :page-size="pageInfo.size"
          @current-change="change"
        />
      </el-col>
    </el-row>
    <addEmployee :dialog-visible.sync="dialogVisible" @addEmployee="getAllDetail" />
    <!-- 头像预览 -->
    <el-dialog :visible.sync="imgDialogSHow" title="头像预览" width="35%">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <assign-role ref="role" :show-dialog="showDialog" />
  </div>
</template>

<script>
import { getAllDetail } from '@/api/employee'
import enumObject from '@/utils/employees'
import { delEmployee } from '@/api/employee'
import addEmployee from './components/addEmployee'
import { formatDate } from '@/filters'
import QRCode from 'qrcode'
import assignRole from './components/assignRole'

export default {
  name: 'Employee',
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      list: [
        { username: '',
          staffPhoto: '',
          mobile: '',
          workNumber: '',
          formOfEmployment: '',
          departmentName: '',
          timeOfEntry: '',
          enableState: '' }
      ],
      pageInfo: {
        page: 1,
        size: 5,
        total: 0
      },
      defaultImg: require('@/assets/common/head.jpg'),
      loading: false,
      dialogVisible: false,
      keysToEng: {
        '姓名': 'username',
        '工号': 'workNumber',
        '手机号': 'mobile',
        '聘用形式': 'formOfEmployment',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      },
      imgDialogSHow: false, // 控制头像二维码弹框的显示隐藏
      showDialog: false
    }
  },
  created() {
    this.getAllDetail()
  },
  methods: {
    // 获取所有员工详细信息列表，分页面
    async getAllDetail() {
      this.loading = true
      const { total, rows } = await getAllDetail(this.pageInfo)
      this.pageInfo.total = total
      this.list = rows
      this.loading = false
    },
    // 点击分页重新获取新的数据
    change(newPage) {
      this.pageInfo.page = newPage
      this.getAllDetail()
    },
    // 聘用模式的转换
    formatterEmployee(row, col, cellValue, index) {
      const obj = enumObject.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmploy(id) {
      try {
        await this.$confirm('确定要删除该员工吗？', {
          type: 'warning'
        })
        this.loading = true
        await delEmployee(id)
        this.getAllDetail()
        this.$message.success('删除用户成功！')
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    // 导出简单excel
    exportToExcel() {
      // 模块懒加载
      import('@/vender/Export2Excel').then(async excel => {
        // 获取整合后的所有员工的列表
        const data = await this.getAllInfo()
        // console.log(data)
        // console.log(data)
        excel.export_json_to_excel({
          header: Object.keys(this.keysToEng),
          data,
          filename: '员工信息表'
        })
      })
    },
    // 导出复杂excel表格
    comExportToExcel() {
      // 模块懒加载
      import('@/vender/Export2Excel').then(async excel => {
        // 获取整合后的所有员工的列表
        const data = await this.getAllInfo()
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        // console.log(data)
        // debugger
        excel.export_json_to_excel({
          header: Object.keys(this.keysToEng),
          multiHeader,
          merges,
          data,
          filename: '员工信息表'
        })
      })
    },
    // 将获取到的数据进行格式的转换 [{}] => [[]]
    dataFormat(list) {
      return list.map(obj => {
        // console.log(obj)
        return Object.keys(this.keysToEng).map(item => {
          // 对入职时间和转正时间以及聘用形式进行搭配
          if (item === '入职日期' || item === '转正日期') {
            return formatDate(obj[this.keysToEng[item]])
          } else if (item === '聘用形式') {
            const type = enumObject.hireType.find(value => value.id === Number(obj[this.keysToEng[item]]))
            return type ? type.value : '未知'
          }
          return obj[this.keysToEng[item]]
        })
      })
    },
    // 获取所有员工列表数据，整合数据，并将数据进行格式转换
    async getAllInfo() {
      const { rows } = await getAllDetail(
        { page: 1,
          size: this.pageInfo.total
        }
      )
      // console.log(rows) // [{}] => [[]]，需要根据表头的顺序进行转换
      return this.dataFormat(rows)
    },
    // 预览图片 二维码
    preview(url) {
      console.log(url)
      if (url.trim()) {
        // 渲染是异步的，数据修改是同步的，代码从上向下是同步的，应该在会话框的渲染修改完成之后在对这个组件进行相关的操作
        this.imgDialogSHow = true
        this.$nextTick(() => {
        // console.log(this.$refs.myCanvas)
          QRCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户没有上传头像，请稍后重试！')
      }
    },
    // 点击角色 分配角色
    async assignRole(id) {
      await this.$refs.role.getDetailInfo(id)
      this.showDialog = true
    },
    filterHandler(value, row, column) {
      const property = column['property']
      console.log(property, value)
      return row[property] === value
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .avator  {
  .cell {
    text-overflow: unset;
  }
}
.el-pagination{
  text-align: right;
  margin-top: 10px;
}
::v-deep .cell {
  .el-switch.is-disabled  {
  .el-switch__core{
    cursor: default;
  }
}
}
</style>
